package com.syqc.monitor.ui

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.provider.MediaStore
import androidx.activity.result.ActivityResult
import androidx.core.view.isVisible
import com.google.zxing.Result
import com.gyf.immersionbar.ktx.immersionBar
import com.king.zxing.CameraScan
import com.king.zxing.CameraScan.OnScanResultCallback
import com.king.zxing.DefaultCameraScan
import com.king.zxing.util.CodeUtils
import com.king.zxing.util.PermissionUtils
import com.permissionx.guolindev.PermissionX
import com.syqc.comlib.base.BaseActivity
import com.syqc.comlib.databinding.IncludeToolbarBinding
import com.syqc.comlib.utils.ActivityResultUtil.registerResult
import com.syqc.comlib.utils.Language
import com.syqc.comlib.utils.ToolbarHelper
import com.syqc.comlib.utils.setResultTo
import com.syqc.comlib.utils.toast
import com.syqc.monitor.R
import com.syqc.monitor.databinding.ActivityScanQrBinding
import com.syqc.utils.Keys
import kotlin.concurrent.thread


/**
 *@Author Jasper
 *@Time   2021/1/20
 *@Desc   扫码
 */
class ScanQrExteActivity : BaseActivity<ActivityScanQrBinding>(ActivityScanQrBinding::inflate),
    OnScanResultCallback {
    private var mCameraScan: CameraScan? = null
    override fun initView() {
        mToastHandle = DataHandle(Looper.getMainLooper())
        val toolbarVB = IncludeToolbarBinding.bind(binding.root)
        immersionBar { titleBar(toolbarVB.mToolbar) }
        val title = intent.getStringExtra(Keys.INTENT_TITLE) ?: ""
        val scaTitle = "$title ${getString(R.string.title_other_scan_)}"
        ToolbarHelper.setToolbar(this, scaTitle)

        if (Language.isEnglish()) binding.ivScanPhoto.setImageResource(R.mipmap.ic_scan_photo_e)
        initCameraScan()
        startCamera()
    }

    override fun setListener() {
        binding.ivFlashlight.setOnClickListener { toggleTorchState() }
        binding.ivScanPhoto.setOnClickListener {
            getPhotoPermission()
        }
    }

    /**
     * 此处处理扫码结果逻辑
     */
    override fun onScanResultCallback(result: Result?): Boolean {
        mCameraScan?.setAnalyzeImage(false)
        if (result == null || result.text.isNullOrEmpty()) {
            mToastHandle?.sendEmptyMessage(0)
            mCameraScan?.setAnalyzeImage(true)
            return true
        }
        setResultTo(this, RESULT_OK) {
            putExtra("ScanResult", result.text)
        }
        finish()
        finish()
        return true
    }

    private fun showToast() {
        if (!isFinishing) {
            if (isFirst) {
                isFirst = false
                mToastHandle?.sendEmptyMessage(0)
            } else {
                mToastHandle?.sendEmptyMessageDelayed(0, 2000)
            }

        }
    }

    /**
     * 初始化CameraScan
     */
    private fun initCameraScan() {
        mCameraScan = DefaultCameraScan(this, binding.previewView)
        mCameraScan?.setOnScanResultCallback(this)
    }

    //是否第一次弹窗
    private var isFirst = true

    /**
     * 启动相机预览
     */
    private fun startCamera() {
        if (mCameraScan != null) {
            if (PermissionUtils.checkPermission(this, Manifest.permission.CAMERA)) {
                mCameraScan!!.startCamera()
            } else {
                getCameraPermission()
            }
        }
    }

    private fun startPhotoCode() {
        mCameraScan?.setAnalyzeImage(false)
        val pickIntent = Intent(
            Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI
        )
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        photoLauncher.launch(pickIntent)
    }

    /**
     * 获取相机权限
     */
    private fun getCameraPermission() {
        val requestList = ArrayList<String>()
        requestList.add(Manifest.permission.CAMERA)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestList.add(Manifest.permission.READ_MEDIA_IMAGES)
            requestList.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            requestList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }

        PermissionX.init(this).permissions(requestList)
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    startCamera()
                } else {
                    toast(R.string.toast_no_has_permission)
                }
            }

    }

    /**
     * 获取相机权限
     */
    private fun getPhotoPermission() {
        val requestList = ArrayList<String>()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            requestList.add(Manifest.permission.READ_MEDIA_IMAGES)
            requestList.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            requestList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }

        PermissionX.init(this).permissions(requestList)
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    startPhotoCode()
                } else {
                    toast(R.string.toast_no_has_permission)
                }
            }
    }

    /**
     * 切换闪光灯状态（开启/关闭）
     */
    private fun toggleTorchState() {
        if (mCameraScan != null) {
            val isTorch = mCameraScan!!.isTorchEnabled
            mCameraScan!!.enableTorch(!isTorch)
            binding.ivFlashlight.isSelected = !isTorch
        }
    }

    /**
     * 释放相机
     */
    private fun releaseCamera() {
        mCameraScan?.release()
    }

    private val photoLauncher = registerResult {
        when (it.resultCode) {
            Activity.RESULT_CANCELED -> {
                mCameraScan?.setAnalyzeImage(true)
            }

            Activity.RESULT_OK -> {
                handResult(it)
            }
        }
    }

    private fun handResult(it: ActivityResult) {
        try {
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, it.data?.data)
            //异步解析
            thread {
                val result = CodeUtils.parseQRCode(bitmap)
                if (result.isNullOrEmpty()) {
                    mToastHandle?.sendEmptyMessage(0)
                    mCameraScan?.setAnalyzeImage(true)
                    return@thread
                }

                setResultTo(this, RESULT_OK) {
                    putExtra("ScanResult", result)
                }
                finish()
            }
        } catch (e: Exception) {
            e.printStackTrace()
            mCameraScan?.setAnalyzeImage(true)
        }
    }

    override fun onDestroy() {
        releaseCamera()
        mToastHandle?.removeCallbacksAndMessages(null)
        super.onDestroy()
    }

    //线程处理数据
    private var mToastHandle: DataHandle? = null

    inner class DataHandle(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 0) {
                binding.tvToast.isVisible = true
                mToastHandle?.sendEmptyMessageDelayed(1, 3000)

            } else {
                binding.tvToast.isVisible = false

            }
        }
    }

}